let SWDA_AtbGauge = {};
//=============================================================================
// Scene_Battle
//=============================================================================
SWDA_AtbGauge.Scene_Battle_createAllWindows = Scene_Battle.prototype.createAllWindows;

Scene_Battle.prototype.createAllWindows = function() {
    SWDA_AtbGauge.Scene_Battle_createAllWindows.call(this);
    this.createATBGaugeWindow();
};

Scene_Battle.prototype.createATBGaugeWindow = function() {
    this._atbGaugeWindow = new Window_BattleATB();
    this.addWindow(this._atbGaugeWindow);
};


//=============================================================================
// Window_BattleATB
//=============================================================================

function Window_BattleATB() {
    this.initialize.apply(this, arguments);
}

Window_BattleATB.prototype = Object.create(Window_Base.prototype);
Window_BattleATB.prototype.constructor = Window_BattleATB;

Window_BattleATB.prototype.initialize = function() {
    const width = 97;
    const height = 240;
    const x = 8;
    const y = Graphics.boxHeight / 2 - height / 2;
    this._atbActorSprite = [];
    this._atbEnemySprite = [];
    this._actors = null;
    this._enemies = null;
    this._isShow = false;
    Window_Base.prototype.initialize.call(this, x, y, 0, 0);
    this.contentsOpacity = 0;
    this.opacity = 0;
    this._isShow = true;
};

Window_BattleATB.prototype.createContents = function () {
    Window_Base.prototype.createContents.call(this);
    this.createATBGaugeSprite();
    this.createActorATBSprites();
    this.createEnemyATBSprites();
};

Window_BattleATB.prototype.createATBGaugeSprite= function () {
    this._atbGaugeSprites = new Sprite();
    this._atbGaugeSprites.bitmap = ImageManager.loadBitmap('img/system/UI/', 'atbGauge');
    this.addChildAt(this._atbGaugeSprites, 1);
    this._atbGaugeSprites.move(33, 0);
};

Window_BattleATB.prototype.createActorATBSprites= function () {
    this._actors = $gameParty.battleMembers();
    for (let i = 0; i < this._actors.length; i++){
        this._atbActorSprite.push(new Sprite_ATB(this._actors[i],this.startY(), this.endY()));
        this._atbActorSprite[i]._requestRefresh = true;
        this._atbActorSprite[i].x = this.centerX();
        this._atbGaugeSprites.addChild(this._atbActorSprite[i]);
    }
    
};

Window_BattleATB.prototype.createEnemyATBSprites= function () {
    this._enemies = $gameTroop.members();
    for (let i = 0; i < this._enemies.length; i++){
        this._atbEnemySprite.push(new Sprite_ATB(this._enemies[i],this.startY(), this.endY()));
        this._atbEnemySprite[i]._requestRefresh = true;
        this._atbEnemySprite[i].x = this.centerX();
        this._atbGaugeSprites.addChild(this._atbEnemySprite[i]);
    }
    
};
Window_BattleATB.prototype.startY= function () {
    return 216;
};
Window_BattleATB.prototype.endY= function () {
    return 24;
};
Window_BattleATB.prototype.centerX= function () {
    return 16;
};

Window_BattleATB.prototype.update = function() {
    Window_Base.prototype.update.call(this);
    this.updateOpacity();
    this.updateSprites();
    this.updateATBDepth();
};

// 如果队列变更（如宠物加入）则重置图片。
Window_BattleATB.prototype.updateSprites = function() {
    if (this.partyChanged()) {
        this._atbActorSprite = [];
        this._atbGaugeSprites.removeChildren();
        this.createActorATBSprites();
        this.createEnemyATBSprites();
    }
};

Window_BattleATB.prototype.partyChanged = function() {
    // 如果长度不一致，强制刷新
    if ($gameParty.battleMembers().length != this._actors.length)
        return true;
    // 如果内容不一致，强制刷新
    for (let i = 0; i<$gameParty.battleMembers().length; i++){
        let curBattler = $gameParty.battleMembers()[i];
        let lastBattler = this._actors[i];
        // 如果都是宠物，宠物不一致，则重置
        if (curBattler.isPet() && lastBattler.isPet()) {
            if (curBattler._baseId != lastBattler._baseId){
                return true;
            } else if (curBattler._masterActorId != lastBattler._masterActorId){
                return true;
            } else if (curBattler._indexForMaster != lastBattler._indexForMaster){
                return true;
            }
        // 如果都是角色，角色变化，则重置
        } else if (!curBattler.isPet() && !lastBattler.isPet()) {
            if (curBattler.actorId() != lastBattler.actorId()){
                return true;
            }
        // 如果是角色、宠物互换（？），则重置
        } else {
            return true;
        }
    }
    return false;
};


Window_BattleATB.prototype.updateOpacity = function() {
    if (this.isShowWindow()) {
      this.contentsOpacity += 255/30;
    } else {
      this.contentsOpacity -= 255/30;
    }
    this.contentsOpacity = this.contentsOpacity.clamp(0, 255);
    this._atbGaugeSprites.opacity = this.contentsOpacity;
};

Window_BattleATB.prototype.isShowWindow = function() {
    if(BattleManager.isBattleEnd()||BattleManager.isEscaped()||$gameMessage.isBusy()||BattleManager._phase === 'start'){
        this._isShow = false;
    }else{
        this._isShow = true;
    }
    return this._isShow;
};

Window_BattleATB.prototype.updateATBDepth = function() {
    if (this._atbGaugeSprites && this._atbActorSprite && this._atbEnemySprite){
        this._atbGaugeSprites.children.sort(this.atbDepthCompare);
    }
}

// 显示优先级排序
Window_BattleATB.prototype.atbDepthCompare = function (a, b) {
    if (a.isBattlerATBFastest())  {return 1;}
    if (b.isBattlerATBFastest())  {return -1;}
    if (a.isBattlerSelected() && !b.isBattlerSelected())  { return 1; }
    if (b.isBattlerSelected() && !a.isBattlerSelected())  { return -1; }
    if (a.battler().isATBCharging() && !b.battler().isATBCharging())  { return 1; }
    if (b.battler().isATBCharging() && !a.battler().isATBCharging())  { return -1; }
    if (a.battler().atbRate() >= 1 && b.battler().atbRate() < 1)  { return 1; }
    if (b.battler().atbRate() >= 1 && a.battler().atbRate() < 1)  { return -1; }
    if (a.y < b.y) { return 1; }
    if (a.y > b.y) { return -1; }
    return 0;
};

//=============================================================================
// 隐藏角色状态窗口的ATB条
//=============================================================================
Window_BattleStatus.prototype.drawAllATBGauges = function () {
};

Window_BattleStatus.prototype.redrawATB = function () {
};